<template>
  <div class="global-container">
    <Atable
      ref="expandTable"
      :tableData="tableData"
      :tableModel="tableModel"
      v-loading="loading"
    >
      <template #expand="{ row }">
        <FormTable
          style="padding: 0px 10px 0px 40px"
          :formData="row.formData"
          :tableModel="formTableModel"
          :disabled="false"
        >
          <template #upload="scope">
            <BtnUpload
              style="width: 100%; padding: 0"
              btn-text="上传模板"
              :business-table="'SYS_FILE_RULE'"
              :business-id="
                row.formData.tableData[scope.index] &&
                row.formData.tableData[scope.index].id
              "
              :sub-type="
                row.formData.tableData[scope.index] &&
                row.formData.tableData[scope.index].id
              "
              :value="
                row.formData.tableData[scope.index] &&
                [row.formData.tableData[scope.index].temDownloadUrl]
              "
              :disabled="row.formData.disabledArr.includes(scope.index)"
              @change="
                handleUploadChange(
                  scope.index,
                  row.formData.tableData[scope.index],
                  $event,
                )
              "
            />
          </template>
          <template #actions="scope">
            <el-button
              v-if="row.formData.disabledArr.includes(scope.index)"
              size="mini"
              type="text"
              class="operation-button"
              @click.stop="
                editItem({ row, rowChild: scope.row, index: scope.index })
              "
            >
              <span>编辑</span>
            </el-button>
            <el-button
              v-else
              size="mini"
              type="text"
              class="operation-button"
              @click.stop="
                saveItem({ row, rowChild: scope.row, index: scope.index })
              "
            >
              <span>保存</span>
            </el-button>
            <el-button
                v-if="row.formData.disabledArr.includes(scope.index)"
              size="mini"
              type="text"
              class="operation-button"
              @click.stop="
                deleteItemById({ row, rowChild: scope.row, index: scope.index })
              "
            >
              <span>删除</span>
            </el-button>
            <el-button
              v-else-if="scope.row.mode === 'add'"
              size="mini"
              type="text"
              class="operation-button"
              @click.stop="
                cancelAdd({ row, index: scope.index })
              ">
              <span>取消</span>
            </el-button>
            <el-button
              v-else
              size="mini"
              type="text"
              class="operation-button"
              @click.stop="
                cancelEdit({ row, index: scope.index })
              ">
              <span>取消</span>
            </el-button>
          </template>
        </FormTable>
      </template>
      <template #actions="{ row }">
        <el-button @click="add(row)" type="primary" size="small"
          >增加</el-button
        >
      </template>
    </Atable>
  </div>
</template>
<script>
import Atable from '@/components/Table/Atable';
import FormTable from '@/components/Table/FormTable';
import BtnUpload from '@/components/Upload/BtnUpload';
import businessApi from '@/api/business';
import materialData from "@/assets/js/materialData";
export default {
  components: {
    Atable,
    FormTable,
    BtnUpload,
  },
  data() {
    return {
      loading: false,
      searchData: {
        pageNum: 1,
        pageSize: 10,
      },
      tableData: [],
      // table fields
      tableModel: [
        {
          type: 'expand',
          slot: 'expand',
        },
        {
          type: 'index',
          label: '序号',
        },
        {
          prop: 'code',
          label: '事项编号',
        },
        {
          prop: 'name',
          label: '事项名称',
          width: '400px',
        },
        {
          prop: 'num',
          label: '材料数量',
        },
        {
          prop: 'actions',
          label: '操作',
          slot: 'actions',
        },
      ],
      // form fields
      formTableModel: [
        {
          label: '序号',
          prop: 'sort',
          width: '100',
          number: true,
        },
        {
          label: '提交材料名称',
          prop: 'ruleName',
          minWidth: '200',
        },
        {
          label: '原件/ 复印件',
          prop: 'copyOrOri',
          select: true,
          options: [
            { label: '原件', value: '1' },
            { label: '复印件', value: '2' },
          ],
        },
        {
          label: '是否必要',
          prop: 'required',
          select: true,
          options: [
            { label: '是', value: '1' },
            { label: '否', value: '2' },
          ],
        },
        {
          label: '提交材料类型',
          prop: 'fileType',
          select: true,
          options: [
            { label: '电子', value: '1' },
            { label: '纸质', value: '2' },
          ],
        },
        {
          label: '纸质文件份数',
          prop: 'number',
          number: true,
        },
        {
          label: '备注',
          prop: 'remarks',
          textarea: true,
          width: '200',
        },
        {
          label: '模板下载',
          prop: 'temDownloadUrl',
          slot: 'upload',
          width: '200',
        },
        {
          label: '操作',
          slot: 'actions',
        },
      ],
    };
  },
  mounted() {
    this.getTable();
  },
  computed: {
    userType() {
      return this.$store.state.user.userInfo.userType;
    },
    materialTable() {
      return materialData.materialData;
    }
  },
  methods: {
    async getTable() {
      this.loading = true;
      this.getTables();
    },
    reset() {
      this.searchData = {};
    },
    // 添加
    add(row) {
      this.$refs.expandTable.toggleRowExpansion(row, true);
      if (row.formData.disabledArr.length === row.formData.tableData.length) {
        row.formData.tableData.push({
          id: this.uuid(),
          bussType: row.bussType,
          mode: 'add'
        });
      } else {
        this.$message.warning('请先保存编辑的一列!');
      }
    },
    // 保存
    saveItem({ row, index }) {
      row.formData.disabledArr.push(index);
      businessApi.saveFileRule(row.formData.tableData[index]).then((res) => {
        if (res) {
          this.$message.success('保存成功!');
          row.num = row.formData.tableData.length;
        } else {
          this.deleteItem({ row, index });
          this.$message.error(res.msg);
        }
      });
    },
    // 修改
    editItem({ row,rowChild, index }) {
      rowChild.mode = 'edit';
      row.formData.disabledArr = row.formData.disabledArr.filter((ite) => {
        return ite != index;
      });
    },
    // 删除
    deleteItem({ row, index }) {
      let delArr = row.formData.disabledArr.filter((ite) => {
        return ite != index;
      });
      row.formData.disabledArr = delArr.map((item) => {
        if (item < index) {
          return item;
        } else {
          return item - 1;
        }
      });
      row.formData.tableData = row.formData.tableData.filter((ite, idx) => {
        return index != idx;
      });
    },
    // 删除
    deleteItemById({ row, rowChild, index }) {
      this.$confirm('确定删除该条数据吗?', '提示').then(() => {
        businessApi.deleteFileRule({ id: rowChild.id }).then((res) => {
          if (res) {
            row.num--;
            this.deleteItem({ row, index });
            this.$message.success('删除成功!');
          }
        });
      });
    },
    // 取消
    cancelAdd({row, index}) {
      this.$confirm('确定取消新增吗?', '提示').then(() => {
        this.deleteItem({ row, index });
      });
    },
    // 取消
    cancelEdit({row}) {
      this.$confirm('确定取消编辑吗?', '提示').then(() => {
        row.formData.disabledArr = row.formData.tableData.map((item, idx) => {
          return idx;
        });
        // this.deleteItem({ row, index });
      });
    },
    // 获取附件信息
    getTables() {
      Promise.all([
        businessApi.getFileRule({
          bussType: '1',
        }),
        businessApi.getFileRule({
          bussType: '2',
        }),
        businessApi.getFileRule({
          bussType: '3',
        }),
        businessApi.getFileRule({
          bussType: '4',
        }),
        businessApi.getFileRule({
          bussType: '5',
        }),
        businessApi.getFileRule({
          bussType: '6',
        }),
        businessApi.getFileRule({
          bussType: '7',
        }),
        businessApi.getFileRule({
          bussType: '8',
        }),
        businessApi.getFileRule({
          bussType: '9',
        }),
        businessApi.getFileRule({
          bussType: 'a',
        }),
        businessApi.getFileRule({
          bussType: 'b',
        }),
        businessApi.getFileRule({
          bussType: 'c',
        }),
        businessApi.getFileRule({
          bussType: 'd',
        }),
        businessApi.getFileRule({
          bussType: 'e',
        }),
      ]).then((res) => {
        let tableData = this.materialTable;
        // map result to tableData
        for (let i = 0; i < res.length; i++) {
          tableData[i].formData.tableData = res[i].records;
          tableData[i].num = res[i].total;
          tableData[i].formData.disabledArr = res[i].records.map(
              (item, index) => {
                return index;
              },
          );
        }
        this.tableData = tableData;
        this.loading = false;
      });
    },
    // 上传文件
    handleUploadChange(index, childRow, event) {
      childRow.temDownloadUrl = event;
    },
    // 生成uuid
    uuid() {
      const uuidUrl = URL.createObjectURL(new Blob());
      const uuid = uuidUrl.toString();
      URL.revokeObjectURL(uuidUrl);
      return uuid.substr(uuid.lastIndexOf('/') + 1).replaceAll('-', '');
    },
  },
};
</script>
<style lang="scss" scoped></style>
